<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>

  <body>
    <script>
      const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('once');
          resolve('success');
        }, 1000);
      });

      const start = Date.now();
      promise.then((res) => {
        console.log(res, Date.now() - start);
      });
      promise.then((res) => {
        console.log(res, Date.now() - start);
        return 1;
      }).then((res) => {
        console.log(res, Date.now() - start);
        return 2;
      }).then((res) => {
        console.log(res, Date.now() - start);
      }).then((res) => {
        console.log(res, Date.now() - start);
      }).then((res) => {
        console.log(res, Date.now() - start);
      }).then((res) => {
        console.log(res, Date.now() - start);
      });
      //promise 的 .then 或者 .catch 可以被调用多次
      //但这里 Promise 构造函数只执行一次。或者说 promise 内部状态一经改变，并且有了一个值，
      //那么后续每次调用 .then 或者 .catch 都会直接拿到该值。

      // 1s之后输出
      // once
      // success 1005
      // success 1005
      // 1 1005
      // 2 1005
      // undefined 1005
      // undefined 1005
      // undefined 1005


      const promise1 = new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('once');
          reject("defeat");
        }, 1000);
      });

      const start1 = Date.now();
      promise1.then(
        (res) => {
          console.log(res, Date.now() - start1);
          return 1;
        },
        (rej)=>{
          console.log("reject1",rej);
          return 1;
      }).then(
        (res) => {
          console.log(res, Date.now() - start1);
          return 2;
        },
        (rej) => {
          console.log("reject2",rej);
          return 2;
      }).then(
        (res) => { 
          console.log(res, Date.now() - start1);
        },
        (rej) => {
          console.log("reject3",rej);
      }).then(
        (res) => {
          console.log(res, Date.now() - start1);
        },
        (rej) =>{
          console.log("reject3",rej);
      });
      // once
      // reject1 defeat
      // 1 1008
      // 2 1008
      // undefined 1008
    </script>
  </body>
</html>
